#
#	redMine - Instant Mobile Feedback (IMF) Plugin
#	Author: Bartłomiej Twardowski
#	Date: 16/06/2010
#

require File.dirname(__FILE__) + '/imf_plugin_app_controller'

class IssueController < IMFPluginApplicationController

  accept_key_auth :get, :create, :set_status

	def get
		
		logger.debug "Getting issue..."
		issue=Issue.find(params[:id])
		
		respond_to do |format|
			format.html { }
          	format.xml  { render(:xml => issue); return }
        end
		
	end

	def create
	
		logger.debug "Creating new issue..."
		
		issue = Issue.new
		
		logger.debug "Creating new issue for project with id: " + params[:issue][:project_id]
		project = Project.find_by_identifier(params[:issue][:project_id])
		issue.project = project
		logger.debug "Project: #{project}"
		
		issue.tracker ||= project.trackers.find((params[:issue] && params[:issue][:tracker_id]) || params[:tracker_id] || :first)
		
		issue.author = User.current
		issue.status ||= IssueStatus.find_by_id(params[:issue][:status_id])|| IssueStatus.default
		issue.start_date = Date.today	
		issue.subject = params[:issue][:subject]
		issue.description = params[:issue][:description]
		
		logger.debug "Saving issue: #{issue}"
		
		if issue.save
			logger.debug "Issue saved to DB."
			
			respond_to do |format|
          		format.html {}
          		format.xml  { render :xml => issue }
	        end
        	return
		else
			logger.debug "Error occured during saving Issue to DB."
	      respond_to do |format|
          	format.html { }
          	format.xml  { render(:xml => issue.errors, :status => :unprocessable_entity); return }
          end
		end
		
		logger.debug "End of creating issue"
		
	end
	
	def set_status
		
		logger.debug "Changing status of issue"
		
		issue=Issue.find(params[:issue][:id])
		status=IssueStatus.find_by_id(params[:issue][:status_id])
		issue.status=status
		out = issue.save

		respond_to do |format|
       		format.html {}
       		format.xml  { render :xml => issue }
	    end		
		
	end
		

end
